import { useState } from "react";
import { message } from "antd";
import instance from "../utils/https";
// import ImgCrop from "antd-img-crop";
// import imageCompression from "browser-image-compression";
// import { ImageUploader, Toast } from "antd-mobile";
import "../../css/Register.less";
import { useNavigate } from "react-router-dom";
// interface FileItem {
//   url: string;
// }
const Register = () => {
  // const [fileList, setFileList] = useState<FileItem[]>([]);
  const Navigate = useNavigate();
  const [formData, setFormData] = useState({
    phone: "",
    password: "",
    confirmPassword: "",
  });
  const [errors, setErrors] = useState({
    phone: "",
    password: "",
    confirmPassword: "",
    img: "",
  });
  // const [imgurl, setimgurl] = useState("");
  // 验证手机号
  const isValidPhoneNumber = (phone: string) => {
    // 中国手机号规则
    const phoneRegex = /^1[3456789]\d{9}$/;


    return phoneRegex.test(phone);
  };
  // const handleLogin = () => {
  //   Navigate("/login");
  // };
  // 表单输入处理
  const handleChange = (e: any) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));

    // 实时验证
    if (name === "phone" && !isValidPhoneNumber(value)) {
      setErrors((prev) => ({ ...prev, phone: "请输入11位正确手机号" }));
    } else if (name === "phone") {
      setErrors((prev) => ({ ...prev, phone: "" }));
    }

    if (name === "confirmPassword" && value !== formData.password) {
      setErrors((prev) => ({
        ...prev,
        confirmPassword: "两次输入的密码不一致",
      }));
    } else if (name === "confirmPassword") {
      setErrors((prev) => ({ ...prev, confirmPassword: "" }));
    }
  };

  // 表单提交处理
  const handleSubmit = async (e: any) => {
    e.preventDefault();

    const { phone, password, confirmPassword } = formData;
    let isValid = true;

    // 验证手机号
    if (!isValidPhoneNumber(phone)) {
      setErrors((prev) => ({ ...prev, phone: "请输入有效的账号" }));
      isValid = false;
    }

    // 验证密码
    if (!password.trim()) {
      setErrors((prev) => ({ ...prev, password: "密码不能为空" }));
      isValid = false;
    }

    // 验证确认密码
    if (password !== confirmPassword) {
      setErrors((prev) => ({
        ...prev,
        confirmPassword: "两次输入的密码不一致",
      }));
      isValid = false;
    }
    // if (imgurl == "") {
    //   message.error("请上传头像");
    //   isValid = false;
    // }
    if (isValid) {
      try {
        const res: any = await instance.post("/register", {
          phoneNum: phone,
          pwd: password,
          // avtor: imgurl,
        });
        if (res.code == 200) {
          message.success("注册成功");
          Navigate("/app/login");
        }
      } catch {
        message.error("该用户已经注册");
      }
    }
  };
  // 压缩图片的函数
  // const compressImage = async (file: File): Promise<File> => {
  //   const options = {
  //     maxSizeMB: 1, // 压缩后的图片最大为 1MB
  //     maxWidthOrHeight: 1920, // 图片宽高最大为 1920px
  //     useWebWorker: true, // 使用 Web Worker 压缩（加快速度）
  //   };
  //   try {
  //     const compressedFile = await imageCompression(file, options);
  //     return compressedFile;
  //   } catch (error) {
  //     console.error("图片压缩失败:", error);
  //     Toast.show("图片压缩失败");
  //     throw error;
  //   }
  // };
  // const uploadHandler = async (file: File) => {
  //   const formData = new FormData();
  //   const compressedFile = await compressImage(file);
  //   formData.append("file", compressedFile);
  //   try {
  //     const res: any = await instance.post("/upload", formData, {
  //       headers: { "Content-Type": "multipart/form-data" },
  //     });
  //     setimgurl("https://zcgjcy.com/api/" + res.path);
  //     return { url: "https://zcgjcy.com/api/" + res.path }; // 假设后端返回图片的 URL
  //   } catch (error) {
  //     Toast.show({ content: "上传失败", icon: "fail" });
  //     return { url: "" };
  //   }
  // };

  return (
    <div className="register-container">
      <h1 className="register-title">用户注册</h1>
      <form className="register-form" onSubmit={handleSubmit}>
        {/* <ImgCrop>
          <ImageUploader
            value={fileList}
            onChange={setFileList} // 更新文件列表
            upload={uploadHandler} // 自定义上传逻辑
            maxCount={1} // 限制只能上传一张图片
            onDelete={() => alert("图片已删除")}
            className="upload-container"
          />
        </ImgCrop> */}

        <div className="form-group">
          <label htmlFor="phone">账号</label>
          <input
            type="text"
            id="phone"
            name="phone"
            placeholder="请输入11位正确的手机号"
            value={formData.phone}
            onChange={handleChange}
          />
          {errors.phone && <p className="error-message">{errors.phone}</p>}
        </div>

        <div className="form-group">
          <label htmlFor="password">密码</label>
          <input
            type="password"
            id="password"
            name="password"
            placeholder="请输入密码"
            value={formData.password}
            onChange={handleChange}
          />
          {errors.password && (
            <p className="error-message">{errors.password}</p>
          )}
        </div>

        <div className="form-group">
          <label htmlFor="confirmPassword">确认密码</label>
          <input
            type="password"
            id="confirmPassword"
            name="confirmPassword"
            placeholder="请再次输入密码"
            value={formData.confirmPassword}
            onChange={handleChange}
          />
          {errors.confirmPassword && (
            <p className="error-message">{errors.confirmPassword}</p>
          )}
        </div>
        <div >
          {/* <button onClick={handleLogin} className="register-button">
            登录
          </button> */}
          <div>
            <p className="p" onClick={() => { Navigate('/app/login') }}>已有账号?去登录</p>
          </div>
          <div style={{width:'100%'}}>
            <button type="submit" className="register-button" style={{width:'100%'}}>
              注册
            </button>
          </div>
        </div>
      </form>
    </div>
  );
};

export default Register;

